<script setup>
import { ref, inject } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
const config = inject('config')

const formatDate = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm')
}

const posts = ref([])
const currentPage = ref(1)

const handlePageChange = (page) => {
  currentPage.value = page
  fetchPosts()
}
const totalPages = ref(5)

const fetchPosts = async () => {
  try {
    const response = await axios.get('/api.php?c=BlogPost&a=getPosts')
    const allPosts = response.data.data
    const itemsPerPage = 6
    totalPages.value = Math.ceil(allPosts.length / itemsPerPage)
    posts.value = allPosts.slice(
      (currentPage.value - 1) * itemsPerPage,
      currentPage.value * itemsPerPage
    )
  } catch (error) {
    console.error('获取文章失败:', error)
  }
}

fetchPosts()
</script>

<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-8 text-gray-800 tracking-tight">{{ config?.latestPostsTitle || '最新文章' }}</h1>
    
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      <article 
        v-for="post in posts"
        :key="post.id"
        class="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1.5"
      >
        <div class="p-6 space-y-4">
          <router-link 
            :to="{ name: 'post', params: { id: post.id } }"
            class="text-xl font-bold text-gray-800 hover:text-blue-600 transition-colors cursor-pointer"
          >
            {{ post.title }}
          </router-link>
          <p class="text-gray-600 mb-4 line-clamp-3">{{ post.excerpt }}</p>
          <div class="flex items-center justify-between text-sm text-gray-500">
            <span>{{ post.author }}</span>
            <span>{{ formatDate(post.created_at) }}</span>
          </div>
        </div>
      </article>
    </div>

    <div class="mt-8 flex justify-center">
      <nav class="flex space-x-2">
        <button 
          v-for="page in totalPages"
          :key="page"
          @click="handlePageChange(page)"
          class="px-4 py-2 rounded-md hover:bg-gray-100"
          :class="{ 'bg-blue-500 text-white hover:bg-blue-600': currentPage === page }"
        >
          {{ page }}
        </button>
      </nav>
    </div>
  </div>
</template>
